const connections = require("../app/database");
class RolesService {
  async updatepermissionService(info) {
    console.log(info);
    const statement = `UPDATE role SET permission_id=? where id = ?;`;
    const res = await connections.execute(statement, [
      info.permission_id,
      +info.role_id,
    ]);
    return res;
  }

  async getPermission_id(userId) {
    // 通过id查询当前角色信息
    // console.log(userId);
    const statement = `SELECT * FROM role WHERE id = ?;`;
    const res = await connections.execute(statement, [userId]);
    const roleInfo = res[0][0];
    // console.log(roleInfo.permission_id);

    // 查询当前角色对应的所有权限
    const statement2 = `select * from permission where ps_id in (${roleInfo.permission_id});`;
    const res2 = await connections.execute(statement2);
    const permissionList = res2[0];

    return {
      name: roleInfo.name,
      des: roleInfo.des,
      permissionId: roleInfo.permission_id,
      permissionList,
    };
  }

  //   获取所有角色列表
  async getRolesList() {
    const statement = `SELECT id,name,des,permission_id FROM role ;`;
    const res = await connections.execute(statement);
    // console.log(res[0]);
    return res[0];
  }

  // 获取当前角色拥有的权限
  async getPowers(ids) {
    ids = ids.split(",");
    // console.log(ids);
    let answers = [];
    for (const id of ids) {
      // console.log(id);
      const statement = `select * from 
    permission_son_father_gp
    where sonid in (?);`;
      const res = await connections.execute(statement, [id]);
      // console.log(res[0]);
      answers.unshift(res[0]);
    }
    // console.log(answers);
    return answers;
  }

  // 获取全部权限
  async getAllPowersService() {
    const statement = `select ps_id id,ps_name name,ps_pid pid,ps_level level from 
    permission`;
    const res = await connections.execute(statement);
    console.log(res);
    return res;
  }

  // 获取全部三级权限
  async getAllPowersListService() {
    const statement = `select * from 
    permission_son_father_gp`;
    const res = await connections.execute(statement);
    console.log(res);
    return res;
  }

  // 插入角色
  async addRoleService(data) {
    // console.log(data);
    const statement = `INSERT INTO role (name,des,permission_id) VALUES (?,?,?);`;
    const res = await connections.execute(statement, [
      data.name,
      data.des,
      "148",
    ]);
    // console.log(res);
    return res;
  }

  // 删除角色
  async deleteRoleById(id) {
    const statement = `DELETE FROM role WHERE id = ?;`;
    const result = await connections.execute(statement, [id]);
    return result;
  }

  // 编辑角色
  async editRoleService(id, roleinfo) {
    console.log(roleinfo);
    const statement = `UPDATE role SET name =?,des=? where id = ?;`;
    const result = await connections.execute(statement, [
      roleinfo.name,
      roleinfo.des,
      id,
    ]);
    // return (JSON.stringify(result[0]));
    // console.log(result);1
    return result;
  }
}

module.exports = new RolesService();
